#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on 2011-6-15

@author: drowning
'''

from jiaju.model import Privilege, Type
from jiaju.common.db import connection

def get_type_list(pid=-1):
    """
                不传sid 为父类型
      pid = 0 获取所有子类型
    """
    cursor = connection.cursor()
    if pid is None:
        sql = "select * from type where pid == -1"
    elif pid == 0:
        sql = "SELECT type1.name AS pname,type2.* AS sname FROM TYPE AS type1,TYPE AS type2 WHERE type1.id = type2.pid  ORDER BY pid;"
    else:
        sql = "select * from type where pid = %s"%pid
    print sql
    return cursor.fetchall(sql=sql)


def get_type_one(id):
    return Type.query(id=id)

def delete_type(id):
    try:
        id = int(id)
        type_vo = Type.load(id = id)
        if type_vo is None : 
            return "此分类不存在"
        cursor = connection.cursor()
        if type_vo.pid == -1:
            """删除子分类,父分类"""
            cursor.execute(sql="delete from type where pid = %s"%id)
        cursor.execute(sql = "delete from type where id = %s"%id)
        return 1
    except:
        return "删除失败"

def add_type(typeinfo):
    id = int(typeinfo.get("id", 0))
    name = typeinfo.get("name")
    pid = typeinfo.get("pid")
    orders = typeinfo.get("orders")
    try:
        if name == "":
            return "类型名称为空"
        pid = int(pid)
        if pid < -1 : 
            return "父分类错误"
        orders = int(orders)
        if orders < 0:
            return "排名不应该小于0"
        code = 1
        if id:
            type_vo = Type.load(id=id)
            code = 2
        else:
            check_type = Type.load(name=name)
            if check_type is not None:
                return "此类型名已经存在"
            type_vo = Type()
        type_vo.pid = pid
        type_vo.orders = orders
        type_vo.name=name
        type_vo.persist()
        return code
    except:
        raise "转换int出错"
    
    
if __name__ == "__main__":
    delete_type('5')